var UUID = require('uuid-js');

/**
 * 获取文件扩展名
 * @param {String} path
 * @returns {String}
 */
module.exports.getExtName = function (path) {
  if (!path) {
    return '';
  }
  var point = path.lastIndexOf('.');
  if (point < 0 && point == path.length - 1) {
    return '';
  }
  var start = point + 1;
  return path.substr(start);
};

/**
 * 创建随机ID
 * @returns {string}
 */
module.exports.createRandomId = function () {
  return UUID.create(4);
};

/**
 * 时间格式化
 * @param {Number} timestamp 时间戳
 * @param {String} fmt 格式化
 * @returns {String}
 * @example
 * var time1 = new Date().Format('yyyy-MM-dd');
 * var time2 = new Date().Format('yyyy-MM-dd HH:mm:ss');
 */
module.exports.formatTime = function (timestamp, fmt) {
  var now = new Date(timestamp);
  var o = {
    'M+': now.getMonth() + 1, //月份
    'd+': now.getDate(), //日
    'H+': now.getHours(), //小时
    'm+': now.getMinutes(), //分
    's+': now.getSeconds(), //秒
    'q+': Math.floor((now.getMonth() + 3) / 3), //季度
    'S': now.getMilliseconds() //毫秒
  };

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (now.getFullYear() + '').substr(4 - RegExp.$1.length));
  }

  for (var k in o) {
    if (o.hasOwnProperty(k)) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
      }
    }
  }
  return fmt;
};

var supportHtml5 = true;
if (!window.FileReader || !document.createElement('canvas').getContext) {
  supportHtml5 = false;
}
/**
 * 判断是否支持html5,简单判断，用FileReader和canvas作为依据
 * @returns {boolean}
 */
module.exports.html5Supported = function () {
  return supportHtml5;
};

module.exports.parseQuery = function (url) {
  var qindex = url.indexOf('?');
  var search = url.substr(qindex + 1);
  var query = {};
  var all = search.split('&');
  for (var i = 0; i < all.length; i++) {
    var item = all[i].split('=');
    var key = item[0];
    if (key) {
      query[item[0]] = item[1];
    }
  }
  return query;
};
